package person.drf.shop.product.jucTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 题目：现在两个线程，可以操作初始值为0的一个变量
 *      实现一个线程对该变量加，一个线程对该变量减1，
 *      实现交替，来10轮，变量初始值为零。
 *
 */
class NewAirConditioner{    //资源类
    private int number = 0;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
         try {
             //1.判断
             while(number!=0){
                 condition.await(); //this.wait();
             }
             //2.干活
             number++;
             System.out.println(Thread.currentThread().getName()+"--"+number);
             //3.通知
             condition.signalAll();  //this.notifyAll();
          }catch (Exception e){
             e.printStackTrace();
          }finally {
             lock.unlock();
         }
    }

    public synchronized void decrement() throws InterruptedException {
        lock.lock();
         try {
             //1.判断
             while(number==0){
                 condition.await(); //this.wait();
             }
             //2.干活
             number--;
             System.out.println(Thread.currentThread().getName()+"--"+number);
             //3.通知
             condition.signalAll();  //this.notifyAll();
          }catch (Exception e){
             e.printStackTrace();
          }finally {
             lock.unlock();
         }

    }
}

public class NewProConDemo {
    public static void main(String[] args) {
        NewAirConditioner airConditioner = new NewAirConditioner();

         new Thread(()->{
             for (int i = 0; i < 10; i++) {
                 try {
                     airConditioner.increment();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         },"A").start();  //  +

         new Thread(()->{
             for (int i = 0; i < 10; i++) {
                 try {
                     airConditioner.increment();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         },"B").start();  //  +

         new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();  //  -

         new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();  //  -
    }
}
